package com.beemans.corekit.utils;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import androidx.core.util.Consumer;

import com.beemans.corekit.integration.toolkit.AppUtils;
import com.beemans.corekit.ui.activity.AllFileAccessPermissionActivity;
import com.beemans.corekit.ui.activity.PermissionActivity;

import java.util.Arrays;

public final class PermissionUtils {

    /**
     * @return 是否已开启通知权限
     */
    public static boolean areNotificationsEnabled() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            return Arrays.stream(getPostNotificationPermissions()).anyMatch(PermissionUtils::isPermissionGranted);
        }
        final NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(AppUtils.getApp());
        return notificationManagerCompat.areNotificationsEnabled();
    }

    @NonNull
    public static String[] getPostNotificationPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            return new String[]{Manifest.permission.POST_NOTIFICATIONS};
        }
        return new String[]{};
    }

    /**
     * 检查是否有所有文件访问权限（Android 11+）
     */
    @RequiresApi(api = Build.VERSION_CODES.R)
    public static boolean hasAllFileAccessPermission() {
        return Environment.isExternalStorageManager();
    }

    /**
     * 请求所有文件访问权限（Android 11+的MANAGE_EXTERNAL_STORAGE权限）
     *
     * @param callback 权限申请结果回调，true表示已获得权限，false表示未获得权限
     */
    @RequiresApi(api = Build.VERSION_CODES.R)
    public static void requestAllFileAccessPermission(@NonNull Consumer<Boolean> callback) {
        if (Environment.isExternalStorageManager()) {
            // 已有权限，直接回调
            callback.accept(true);
            return;
        }
        // 启动权限申请Activity
        AllFileAccessPermissionActivity.start(callback);
    }

    /**
     * 请求通知栏权限
     */
    public static void requestNotificationPermission(@NonNull Consumer<Boolean> consumer) {
        if (areNotificationsEnabled()) {
            consumer.accept(true);
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            PermissionActivity.start(getPostNotificationPermissions(), () -> consumer.accept(areNotificationsEnabled()));
        } else {
            consumer.accept(areNotificationsEnabled());
        }
    }

    /**
     * @return 校验权限是否都授权
     */
    private static boolean isPermissionGranted(@NonNull String permission) {
        return ContextCompat.checkSelfPermission(AppUtils.getApp(), permission) == PackageManager.PERMISSION_GRANTED;
    }
}